<template>
  <div class="parent">
    <!-- <p class="titleP" :style="{ color: type == 'dark' ? '#FFFFFF' : '#393939' }">{{ title }}</p> -->
    <div v-if="isShowEcharts && ooctag" class="tasks-total-content-legend">
      <div class="legend-item">
        <span class="legend-icon background-done" />
        <span :style="{ color: type == 'dark' ? '#FFFFFF' : '#393939' }" class="legend-text">OOS:{{ totalOosCount }}</span>
      </div>
      <div class="legend-item">
        <span class="legend-icon background-done2" />
        <span :style="{ color: type == 'dark' ? '#FFFFFF' : '#393939' }" class="legend-text">OOC:{{ totalOocCount }}</span>
      </div>
      <div class="legend-item">
        <span class="legend-icon background-done3" />
        <span :style="{ color: type == 'dark' ? '#FFFFFF' : '#393939' }" class="legend-text">OOW:{{ totalOowCount }}</span>
      </div>
    </div>
    <echartsDom v-if="isShowEcharts" style="width: 100%; height: 100%" :width="'100%'" :height="'100%'" :option="option" :type="type" />
    <div v-else>
      <px-empty :image-size="50" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, toRefs, watch } from "vue";
import echartsDom from "./echartsDom.vue";

import { spcIndicatorqueryResultCount, spcquerySpcAnalysis } from "@/api/spc";
const props = defineProps({
  width: {
    type: String,
    default: ""
  },
  height: {
    type: String,
    default: ""
  },
  type: {
    type: String,
    default: ""
  },
  jobId: {
    type: String,
    default: ""
  },
  color: {
    type: String,
    default: ""
  },
  title: {
    type: String,
    default: ""
  },
  unit: {
    type: String,
    default: ""
  },
  ooctag: {
    type: Boolean,
    default: true
  },
  doubleXaxis: {
    type: Boolean,
    default: false
  },
  min: {
    type: [Number, String, null],
    default: null
  },
  max: {
    type: [Number, String, null],
    default: null
  }
});
const isShowEcharts = ref(false);
const state = reactive({
  option: {},
  series: [],
  yAxis: [],
  xAxis: [],
  chartsList: []
});
watch(
  () => props.jobId,
  newOption => {
    if (newOption != "") {
      getoptions();
    }
  }
);
const { option, series, yAxis, xAxis, chartsList } = toRefs(state);
function formatDate(timestamp) {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
}

function getHourlyTimes(startDateTime, endDateTime) {
  const result = [];
  const startDate = new Date(startDateTime);
  const endDate = new Date(endDateTime);

  // 如果开始时间不是整点，跳到下一个整点
  if (startDate.getMinutes() !== 0 || startDate.getSeconds() !== 0) {
    startDate.setHours(startDate.getHours() + 1, 0, 0, 0);
  }

  // 遍历整点时间
  let current = new Date(startDate);
  while (current <= endDate) {
    // 格式化为 "HH:00"
    const hours = String(current.getHours()).padStart(2, "0");
    result.push(`${hours}:00`);

    // 增加1小时
    current.setHours(current.getHours() + 1);
  }

  return result;
}

function formatDate2(timestamp) {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${h}:${m}`;
}
const totalOocCount = ref<any>("");
const totalOosCount = ref<any>("");
const totalOowCount = ref<any>("");
const getoptions = () => {
  const end = new Date();
  const start = new Date();
  start.setTime(start.getTime() - 1000 * 60 * 60 * 4);
  spcIndicatorqueryResultCount({
    jobIdList: [props.jobId],
    startTime: formatDate(start),
    endTime: formatDate(end)
  }).then((res: any) => {
    if (res != null) {
      totalOocCount.value = res.totalOocCount;
      totalOosCount.value = res.totalOosCount;
      totalOowCount.value = res.totalOowCount;
    } else {
      totalOocCount.value = 0;
      totalOosCount.value = 0;
      totalOowCount.value = 0;
    }
  });
  let arr = [];
  props.jobId.split(",").forEach(el => {
    arr.push(el);
  });
  spcquerySpcAnalysis({
    pointList: arr,
    timePeriod: "minutes",
    startTime: formatDate(start),
    endTime: formatDate(end)
  }).then((response: any) => {
    // chartsList.value = response && response.length ? response[0].pointValues : [];
    // const doubleXaxisData =
    //   response && response.length
    //     ? response.find(e => e.indicatorName === "主管压差")
    //       ? response.find(e => e.indicatorName === "主管压差").pointValues
    //       : []
    //     : [];
    isShowEcharts.value = true;
    // const minNum = response.sort((a, b) => {
    //   return a.startValue - b.startValue;
    // })[0].startValue;
    // const maxNum = response.sort((a, b) => {
    //   return b.endValue - a.endValue;
    // })[0].endValue;
    const firstXaxis = {
      type: "category",
      boundarGap: false,
      position: "bottom",
      data: getHourlyTimes(formatDate(start), formatDate(end))
    };
    const xaixsData =
      response && response.length
        ? response.map((item, index) => {
            return {
              type: "category",
              boundarGap: false,
              axisLabel: {
                show: false
              },
              axisLine: {
                show: false
              },
              axisTick: {
                show: false
              },
              position: "bottom",
              offset: (index + 1) * 30,
              data:
                item.pointValues && item.pointValues.length > 0
                  ? item.pointValues.map(item => formatDate2(item.time))
                  : ["11:00", "12:00", "13:00", "14:00", "15:00", "16:00"]
            };
          })
        : [];
    xAxis.value = [...xaixsData, firstXaxis];
    yAxis.value = response.map((item: any, index) => {
      if (item.pointValues && item.pointValues.length > 0) {
        return {
          name: props.title != null ? `${props.title}(${props.unit ? props.unit : "-"})` : "空",
          type: "value",
          nameLocation: "end",
          nameTextStyle: {
            align: "left"
          },
          // nameGap: 70, //轴线距离
          // nameRotate: 90, //字体选择角度
          axisLine: {
            show: true,
            lineStyle: {
              type: "solid"
            }
          },
          // min: minNum,
          // max: maxNum,
          max: function (value) {
            let max = Number(props.max && props.max != null ? Number(props.max) : Number(value.max).toFixed(2));
            let min = Number(props.min && props.min != null ? Number(props.min) : Number(value.min).toFixed(2));
            let poor = Math.abs(max - min);
            let extreme = Number((poor / 3).toFixed(2));
            let result = max + Math.round(extreme);
            return props.max && props.max != null ? max : Number(result.toFixed(2));
          },
          min: function (value) {
            let max = Number(props.max && props.max != null ? Number(props.max) : Number(value.max).toFixed(2));
            let min = Number(props.min && props.min != null ? Number(props.min) : Number(value.min).toFixed(2));
            let poor = Math.abs(max - min);
            let extreme = Number((poor / 3).toFixed(2));
            let result = min - Math.round(extreme);
            return props.min && props.min != null ? min : Number(result.toFixed(2));
          },
          axisLabel: {
            interval: item.step
          }
        };
      } else {
        return {
          name: "",
          type: "value",
          // nameGap: 70, //轴线距离
          // nameRotate: 90, //字体选择角度
          axisLine: {
            show: true,
            lineStyle: {
              type: "solid"
            }
          }
        };
      }
    });
    series.value = response.map((item, index) => {
      return {
        data: item.pointValues && item.pointValues.length > 0 ? fillNullsWithPrevious(item.pointValues.map(item => item.value)) : [],
        type: "line",
        name: item.indicatorName || item.pointName,
        areaStyle: {
          opacity: 0.15,
          origin: "start"
        },
        xAxisIndex: index
      };
    });
    // series.value[0].markLine = {
    //   symbol: "none",
    //   data: [
    //     {
    //       name: "LWL值",
    //       yAxis: Number(response[0].uwlValue != null ? response[0].uwlValue : 0),
    //       lineStyle: {
    //         color: "#ffca45",
    //         wideh: "1",
    //         type: "solide"
    //       },
    //       label: {
    //         position: "insideEndBottom",
    //         formatter: `内控要求<${response[0].uwlValue != null ? response[0].uwlValue : ""}${response[0].pointUnit || ""}`,
    //         color: "#ffca45"
    //       }
    //     },
    //     {
    //       name: "UWL值",
    //       yAxis: Number(response[0].lwlValue != null ? response[0].lwlValue : 0),
    //       lineStyle: {
    //         color: "#ffca45",
    //         wideh: "1",
    //         type: "solide"
    //       },
    //       label: {
    //         position: "insideEndTop",
    //         formatter: `内控要求>${response[0].lwlValue != null ? response[0].lwlValue : ""}${response[0].pointUnit || ""}`,
    //         color: "#ffca45"
    //       }
    //     }
    //   ]
    // };
    setdata();
  });
};

const fillNullsWithPrevious = data => {
  let previousNonNull = null;
  return data.map(item => {
    if (item == null) {
      return previousNonNull;
    } else {
      previousNonNull = item;
      return item;
    }
  });
};

const setdata = () => {
  option.value = {
    backgroundColor: props.type == "dark" ? "#001e3b" : "",
    color: [props.color, "#35CECB", "#F59E0B"],
    grid: {
      left: "10px",
      top: props.ooctag ? "60px" : "40px",
      right: "10px",
      bottom: "0px",
      containLabel: true
    },
    // legend: {
    //   type: "scroll", // 设置图例分页类型为滚动
    //   icon: "rect",
    //   orient: "horizontal", // 水平排列
    //   data: series.value.map(e => e.name) || []
    // },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    xAxis: xAxis.value,
    yAxis: yAxis.value && yAxis.value.length ? yAxis.value[0] : {},
    series: series.value
  };
};
</script>

<style scoped lang="scss">
.parent {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.titleP {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 11;
  width: 100%;
  margin-bottom: 10px;
  font-size: 12px;
  color: #393939;
  text-align: left;
}

.tasks-total-content-legend {
  position: absolute;
  top: 28px;
  left: 18px;
  z-index: 11;
  display: flex;
  gap: 16px;
  align-items: center;

  .legend-item {
    display: flex;
    gap: 8px;
    align-items: center;

    .legend-text {
      font-size: 12px;
      line-height: 1;
      color: #333;
      white-space: nowrap;
    }

    .legend-icon {
      width: 8px;
      height: 8px;
      border-radius: 50%;
    }

    .background-done {
      background: #ff4355;
    }

    .background-done2 {
      background: #28d892;
    }

    .background-done3 {
      background: #ffca45;
    }
  }
}
</style>
